package com.example.gitproject.controller;

import com.example.gitproject.Entity.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {




@RequestMapping("/fileUpload")
    public Result fileUpload(MultipartFile[] files, HttpServletRequest request){
    for (MultipartFile file:files){
        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf("."));     // xxx  .  jpg
        if (".jpg".equalsIgnoreCase(substring)){
            return new Result(false,"上传失败，需要上传jpg格式图片");
        }

        filename =  UUID.randomUUID() + substring;  // 避免重名文件出现
        String dirpath = "src/main/resources/backend/upload";

        File filepath = new File(dirpath);
        if (!filepath.exists()){  //路径不存在 就生成路径
            filepath.mkdirs();
        }

        try {
            file.transferTo(new File(filepath.getCanonicalFile()+"/"+filename));  //上传文件
            return new Result(true,"/backend/upload"+filename);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,"上传失败");
        }
    }

   return new Result(false,"上传失败");
    }





}
